package com.jn.rxjava.views;

import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.jn.rxjava.R;

import com.jn.rxjava.adapter.ForecastAdapter;
import com.jn.rxjava.model.WeatherResponse;
import com.jn.rxjava.service.WeatherRepository;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class WeatherActivity extends AppCompatActivity {
    private ImageView weatherIcon;
    private TextView temperatureView;
    private TextView conditionView;
    private TextView tipsView;
    private RecyclerView forecastRecyclerView;
    private CompositeDisposable disposables = new CompositeDisposable();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weather);

        weatherIcon = findViewById(R.id.weatherIcon);
        temperatureView = findViewById(R.id.temperature);
        conditionView = findViewById(R.id.condition);
        tipsView = findViewById(R.id.tips);
        forecastRecyclerView = findViewById(R.id.forecastList);

        WeatherRepository repository = new WeatherRepository();
        disposables.add(repository.getWeatherInfo("郑州市")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this::displayWeatherInfo, this::handleError));
    }



    private void displayWeatherInfo(WeatherResponse response) {
        if (response != null && response.getResult() != null) {
            WeatherResponse.Result result = response.getResult();
            temperatureView.setText(String.format("%.1f°C", result.getCurrentTemperature()));
            conditionView.setText(result.getCurrentCondition());
            tipsView.setText(result.getTips());

            Glide.with(this)
                    .load("URL_TO_WEATHER_ICON") // Replace with actual icon URL
                    .into(weatherIcon);

            ForecastAdapter adapter = new ForecastAdapter(result.getForecastList());
            forecastRecyclerView.setAdapter(adapter);
        }
    }

    private void handleError(Throwable throwable) {
        // Handle error
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        disposables.clear();
    }
}